package com.wh.wisdomsite.xbox.server.controller.ba;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.ba.entity.Menu;
import com.wh.wisdomsite.xbox.ba.entity.MenuRole;
import com.wh.wisdomsite.xbox.ba.entity.Role;
import com.wh.wisdomsite.xbox.ba.entity.RoleCompany;
import com.wh.wisdomsite.xbox.ba.service.*;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.ba.RoleIn;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.us.entity.Company;
import com.wh.wisdomsite.xbox.us.entity.User;
import com.wh.wisdomsite.xbox.us.service.IUserService;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 角色Controller
 *
 * @version V1.0
 * @Package: com.wh.wisdomsite.xbox.server.controller.us
 * @author: 丁奕
 * @date: 2018-08-03 11:55
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 **/
@Controller
@RequestMapping(value = "/role")
public class RoleController {

    private static final Log logger = LogFactory.getLog(RoleController.class);

    @Autowired
    private IRoleService iRoleService;

    @Autowired
    private IRoleCompanyService iRoleCompanyService;

    @Autowired
    private IMenuRoleService iMenuRoleService;

    @Autowired
    private IMenuService iMenuService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IFileService iFileService;

    /**
     * 页面跳转
     * @return
     */
    @RequiresPermissions("rules:ba_role_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index(HttpServletRequest request){
        request.setAttribute("isSysAdmin", UserUtils.isSysAdmin());
        return "/ba/role/roleList";
    }

    /**
     * 获取角色集合
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:ba_role_find")
    @RequestMapping(value = "/roleList.do")
    public void roleList(HttpServletResponse response, RoleIn in){
        try {
            logger.info("加载角色数据列表-->>开始");
            //设置分页
            if(in.getPage() == 0) in.setPage(1);
            if(in.getRows() == 0) in.setRows(10);
            Page<Role> page = new Page<Role>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<Role> ewRole = new EntityWrapper<Role>();
            ewRole.setEntity(new Role());
            if(StringUtils.isNotEmpty(in.getName())){
                ewRole.like("name", in.getName());
            }
            if(StringUtils.isNotEmpty(in.getDataScope())){
                ewRole.eq("dataScope", in.getDataScope());
            }
            if(StringUtils.isNotEmpty(in.getIsSys())){
                ewRole.eq("isSys", in.getIsSys());
            }
            if(StringUtils.isNotEmpty(in.getUseable())){
                ewRole.eq("useable", in.getUseable());
            }
            if(!UserUtils.isSysAdmin()){
                Company company = UserUtils.getCurrentUserParentCompany();
                if(company != null && company.getCompanyId() != null){
                    ewRole.eq("rc.companyId", company.getCompanyId());
                    ewRole.or();
                    ewRole.eq("r.isSys", "1");
                    ewRole.eq("r.useable", "1");
                    ewRole.ne("r.roId","0");
                }
            }
            ewRole.groupBy("r.roId");
            ewRole.orderBy("createDate", true);
            Page<Map<String, Object>> roleMapPage = iRoleService.getMapsPage(page, ewRole);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if(roleMapPage.getRecords().size() > 0){
                for(Map<String, Object> role : roleMapPage.getRecords()){
                    JSONObject object = new JSONObject(role);
                    object.put("id",role.get("roId"));
                    object.put("dataScope",new JSONObject(role.get("dataScope")));
                    array.put(object);
                }
            }
            json.put("total",roleMapPage.getTotal());
            json.put("rows",array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载角色数据列表-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("加载角色数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 获取当前登录用户所能查出的所有角色List
     * @param response
     */
    @RequestMapping(value = "/getRoleList.do")
    public void getRoleList(HttpServletResponse response){
        try {
            logger.info("加载当前登录用户所能查出的所有角色数据列表-->>开始");
            //获取当前用户的所属总公司
            Company company = UserUtils.getCurrentUserParentCompany();
            List<Map<String, Object>> roleList = iRoleService.selectListByCompanyId(company.getCompanyId());
            JSONArray array = new JSONArray();
            if(roleList.size() > 0){
                for(Map<String, Object> role : roleList){
                    JSONObject object = new JSONObject();
                    object.put("id",role.get("roId"));
                    object.put("text",role.get("name"));
                    array.put(object);
                }
            }
            ResManager.getTextOut(response).print(array);
            logger.info("加载当前登录用户所能查出的所有角色数据列表-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("加载当前登录用户所能查出的所有角色数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 角色详情
     * @param roleIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:ba_role_view")
    @RequestMapping("roleDesc.do")
    public String roleDesc(RoleIn roleIn, HttpServletRequest request) {
        try {
            logger.info("角色详情-->>开始");
            Map<String , Object> role = iRoleService.getMapById(roleIn.getId());
            if(role.get("createBy") != null){
                role.put("createBy", UserMapManager.getUserLoginNameInMap(role.get("createBy").toString()));
            }
            if(role.get("updateBy") != null){
                role.put("updateBy", UserMapManager.getUserLoginNameInMap(role.get("updateBy").toString()));
            }
            request.setAttribute("role", role);
            logger.info("角色详情-->>结束");
        }catch (Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return "/ba/role/roleDesc";
    }

    /**
     * 跳转至添加或修改页面
     * @return
     */
    @RequestMapping("/toRoleOption")
    public String toRoleOption(String id, HttpServletRequest request){
        try {
            logger.info("添加修改角色跳转-->>开始");
            if(StringUtils.isNotEmpty(id)){
                //注入role参数
                Map<String, Object> role = iRoleService.getMapById(id);
                if(role.get("isSys").equals("1") && !UserUtils.isSysAdmin()){
                    throw new Exception("非系统管理员不能修改系统数据");
                }
                List<Menu> menuList = iMenuService.getMenuListByRoleId(id);
                String menuIds = "";
                if(menuList != null && !menuList.isEmpty()){
                    for(Menu menu : menuList){
                        menuIds += menu.getMeId() + ",";
                    }
                }
                //删除menuIds的最后一个逗号
                if(menuIds.lastIndexOf(",") > 0){
                    menuIds = menuIds.substring(0, menuIds.length() - 1);
                }
                request.setAttribute("role", role);
                request.setAttribute("menuIds", menuIds);
            }
            request.setAttribute("isSysAdmin", UserUtils.isSysAdmin());
            logger.info("添加修改角色跳转-->>开始");
        }catch (Exception e){
            e.printStackTrace();
            return "ba/role/roleList";
        }
        return "ba/role/roleOption";
    }

    /**
     * 更新或者修改
     * @param role
     * @param response
     */
    @RequiresPermissions("rules:ba_role_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    @Transactional(rollbackFor = {Exception.class,RuntimeException.class})
    public void save(Role role,String menuIds,HttpServletResponse response){
        try {
            //判断角色是否已经存在,存在即更新.否则为添加
            if(StringUtils.isNotEmpty(role.getRoId())){
                logger.info("修改角色-->>开始");
                role.setUpdateDate(new Date());
                role.setUpdateBy(UserUtils.getCurrentUser().getUsId());
                iRoleService.deleteMenuRoleByRoleId(role.getRoId());
                iRoleService.updateById(role);
                saveMenuRole(menuIds, role.getRoId());
                logger.info("修改角色-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("角色更新成功"));

            }else {
                logger.info("添加角色-->>开始");
                role.setCreateDate(new Date());
                role.setCreateBy(UserUtils.getCurrentUser().getUsId());
                role.setRoId(UUID.randomUUID().toString().replace("-",""));
                //获取当前用户是否有总公司，若有则维护角色公司关系表
                Company company = UserUtils.getCurrentUserParentCompany();
                if(company != null && company.getCompanyId() != null){
                    RoleCompany roleCompany = new RoleCompany();
                    roleCompany.setCompanyId(company.getCompanyId());
                    roleCompany.setRoId(role.getRoId());
                    roleCompany.setRcId(UUID.randomUUID().toString().replace("-",""));
                    iRoleCompanyService.insert(roleCompany);
                }
                iRoleService.insert(role);
                saveMenuRole(menuIds, role.getRoId());
                logger.info("添加角色-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("角色添加成功"));

            }
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("操作角色-->>Exception" + e.getMessage());
        }
    }

    /**
     * 删除角色
     * @param id
     * @param response
     */
    @RequiresPermissions("rules:ba_role_del")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(String id, HttpServletResponse response){
        try{
            logger.info("删除角色-->>开始");
            //判断是否是超级管理员角色
            if(id.equals("0")){
                ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("系统管理员角色不能被删除！"));
                return;
            }
            iRoleService.deleteById(id);
            //删除角色公司关系表数据
            EntityWrapper<RoleCompany> ewRoleCompany = new EntityWrapper<>();
            ewRoleCompany.setEntity(new RoleCompany());
            ewRoleCompany.eq("roId", id);
            iRoleCompanyService.delete(ewRoleCompany);
            logger.info("删除角色-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("角色删除成功"));
        } catch (Exception e){
            e.printStackTrace();
            logger.error("删除角色-->>Exception" + e.getMessage());
        }
    }

    /**
     * 保存所勾选的菜单权限
     * @param menuIds
     * @param roId
     * @throws Exception
     */
    private void saveMenuRole(String menuIds, String roId){
        //添加角色对应的菜单权限
        String[] meIds = menuIds.split(",");
        List<MenuRole> menuRoleList = new ArrayList<>();
        for (String meId : meIds) {
            MenuRole menuRole = new MenuRole();
            menuRole.setMrId(UUID.randomUUID().toString().replace("-",""));
            menuRole.setRoId(roId);
            menuRole.setMeId(meId);
            menuRoleList.add(menuRole);
        }
        if(!menuRoleList.isEmpty()){
            iMenuRoleService.insertBatch(menuRoleList,meIds.length);
        }
    }

    /**
     * 跳转单选用户页面
     * @param roIds
     * @param request
     */
    @RequiresPermissions("rules:ba_role_selUserBtn")
    @RequestMapping(value = "/toSelUser.do", method = RequestMethod.GET)
    public String toSelUser(String roIds,String stepType,HttpServletRequest request){
        request.setAttribute("roIds",roIds);
        request.setAttribute("stepType",stepType);
        return "ba/role/selUserOption";
    }

    /**
     * 跳转多选用户页面
     * @param roIds
     * @param stepType
     * @param request
     */
    @RequiresPermissions("rules:ba_role_selUsersBtn")
    @RequestMapping(value = "/toSelUsers.do", method = RequestMethod.GET)
    public String toSelUsers(String roIds,String stepType,HttpServletRequest request){
        request.setAttribute("roIds",roIds);
        request.setAttribute("stepType",stepType);
        return "ba/role/selUsersOption";
    }

    /**
     * 根据角色id获取获取角色
     * @param roIds
     * @param response  1: 项目部项目经理  2： 项目部副经理  3: 项目部经理  4: 采购部副经理 5: 采购部分管领导 6: 公司总经理
     */
    @RequestMapping(value = "/getRolesByRoleId.do", method = RequestMethod.GET)
    public void getRolesByRoleId(String roIds, String stepType,HttpServletResponse response){
        try{
            logger.info("根据角色id获取获取角色-->>开始");
            String roleName = null;
            switch (stepType){
                case "2" :
                    roleName = "项目部副经理" ;
                    break;
                case "3" :
                    roleName = "项目部经理" ;
                    break;
                case "4" :
                    roleName = "采购部副经理" ;
                    break;
                case "5" :
                    roleName = "采购部分管领导" ;
                    break;
                case "6" :
                    roleName = "公司总经理" ;
                    break;
                default:
                    roleName = "工程部经理" ;
                    break;
            }
            Integer parentCompId = null;
            Company company = UserUtils.getCurrentUserParentCompany();
            if(null != company && null != company.getCompanyId()){
                parentCompId = company.getCompanyId();
            }
            String compId = UserUtils.getCurrentUser().getCompanyId().toString();
            List<Role> roles = iRoleService.getRoleListByNameAndCompId(roleName,compId,parentCompId,roIds);
            JSONArray array = new JSONArray();
            if(roles.size() > 0){
                for (Role role : roles){
                    JSONObject json = new JSONObject();
                    json.put("roId",role.getRoId());
                    json.put("roName",role.getName());
                    array.put(json);
                }
            }
            ResManager.getTextOut(response).print(array);
            logger.info("根据角色id获取获取角色-->>结束");
        } catch (Exception e){
            e.printStackTrace();
            logger.error("根据角色id获取获取角色-->>Exception" + e.getMessage());
        }
    }

    /**
     * 根据角色id获取用户集
     * @param roId
     * @param response
     */
    @RequestMapping(value = "/getUsersByRoleId.do", method = RequestMethod.GET)
    public void getUsersByRoleId(String roId, HttpServletResponse response){
        try{
            logger.info("根据角色id获取用户集-->>开始");
            String usId = UserUtils.getCurrentUser().getUsId();
            List<User> users = iUserService.selectUserByRoleId(roId,usId);
            JSONArray array = new JSONArray();
            if(users.size() > 0){
                for (User user : users){
                    JSONObject json = new JSONObject();
                    json.put("userId",user.getUsId());
                    json.put("loginName",user.getLoginName());
                    String fileId = user.getUserPhoto();
                    String photoUrl = "";

                    /**
                    //获取可用的头像url
                    if(StringUtils.isNotEmpty(fileId)){
                        photoUrl = iFileService.getUrlById(fileId);
                    }

                     **/
                    json.put("photoUrl",photoUrl);
                    array.put(json);
                }
            }
            ResManager.getTextOut(response).print(array);
            logger.info("根据角色id获取用户集-->>结束");
        } catch (Exception e){
            e.printStackTrace();
            logger.error("根据角色id获取用户集-->>Exception" + e.getMessage());
        }
    }
}
